interface baseDataType {
    name: string
    id: string
    parentkey?: string
    children?: baseDataType[]
}

// interface childrenType {
//     name: string
//     id: string
//     parentkey?: string
//     children?: childrenType[]
// }

interface idType {
    id: string
}
const baseData: baseDataType[] = [
    {name: '精灵云', id: '0'},
    {name: '研发部', id: '0-0', parentkey: '0'},
    {name: '财务部', id: '0-1', parentkey: '0'},
    {name: '质量部', id: '0-2', parentkey: '0'},
    {name: '边缘云业务线', id: '0-0-0', parentkey: '0-0'},
    {name: '大数据业务线', id: '0-0-1', parentkey: '0-0'},
    {name: 'devloops业务线', id: '0-0-2', parentkey: '0-0'},
    {name: '仿真业务线', id: '0-0-3', parentkey: '0-0'},
    {name: '审计部', id: '0-1-0', parentkey: '0-1'},
    {name: '会计部', id: '0-1-1', parentkey: '0-1'},
    {name: '测试部', id: '0-2-0', parentkey: '0-2'},
    {name: '运维部', id: '0-2-1', parentkey: '0-2'},
]

const deepClone = <T>(target: T): T => {
    let result
    if(typeof target !== 'object') return target
    if(Array.isArray(target)) {
        result = []
        target.forEach(item => {
            result.push(deepClone(item))
        })
    }else {
        result = {}
        for(let i in target) {
            result[i] = deepClone(target[i])
        }
    }
    return result
}

let cloneData = deepClone(baseData)

// 将对象数组转换成一棵树
let treeList: baseDataType[] = []
const transferTree = (list: baseDataType[]) => {
    list.forEach((item ,i) => {
        item.children = []
        if(!item.parentkey) {
            treeList.push(item)
        }
        list.forEach((item1, j) => {
            if(item.id === item1.parentkey) {
                item.children.push(item1)
            }
        })

    })
    return treeList
}

treeList = transferTree(cloneData)
console.log(treeList);

// 将树扁平化
let treeFlatArr: baseDataType[] = []
const flatTree = (tree: baseDataType[]) => {
    tree.forEach((item, i) => {
        if(!item.parentkey) {
            treeFlatArr.push(item)
            flatTree(item.children)
        }
        if(item.parentkey) {
            treeFlatArr.push(item)
            if(item.children.length !== 0) {
                flatTree(item.children)
            }
        }
    })
    return treeFlatArr
}

treeFlatArr = flatTree(treeList)
console.log(treeFlatArr);

// 获取id数据
let idArr: string[] = []
const getId = (list: baseDataType[], id: string) => {
    idArr.push(id)
    list.forEach((item, i) => {
        if(id === item.id) {
            if(item.parentkey) {
                getId(list, item.parentkey)
            }
        }
    })
    return idArr
}

// 获取传入数组型的ids
let totalArr: Array<string[]> = []
const getIdArr = (list: baseDataType[], ids: string[]): void => {
    ids.forEach((item, i) => {
        idArr = []
        totalArr.push(getId(list, item))

    })
    console.log(totalArr);
}
getIdArr(treeFlatArr, ['0-2-1', '0-2', '0-0-1'])
export {}